//
//  NewPlayHeaderView.swift
//  TianTianBiTing
//
//  Created by Gox mac 2 on 2019/3/12.
//  Copyright © 2019 Gox_WallyDiao. All rights reserved.
//

import UIKit
import StreamingKit
import SQLite

protocol NewPlayHeaderViewDelegate:NSObjectProtocol {
    func playHeaderViewAction()
    func playNextBtnAction(tag:Int)
    func timeBtnAction()
}

class NewPlayHeaderView: UIView {
    var programId:Int = 0
    var musicModel:PlayListModel?
    var timer: Timer?
    var displayLink: CADisplayLink?
    weak var delegate:NewPlayHeaderViewDelegate?
    
    private lazy var imageView:UIImageView = {
        let imageView = UIImageView.init(frame: FRAME_CGFloat(0, 0, SCREEN_WIDTH, SCREEN_SCALE_X(x: 188)))
        return imageView
    }()
    
    private lazy var sliderBackView:UIView = {
        let view = UIView.init(frame: FRAME_CGFloat(0, SCREEN_SCALE_X(x: 188), SCREEN_WIDTH, 25))
        view.backgroundColor = WhiteBackColor
        return view
    }()
    
    private lazy var slider:UISlider = {
        let slider = UISlider(frame: FRAME_CGFloat(75, 10, SCREEN_WIDTH - 150, 20))
        slider.setThumbImage(UIImage(named: "icon_slider"), for: .normal)
        slider.maximumTrackTintColor = RGB(255, 151, 29, 0.38)
        slider.minimumTrackTintColor = RGB(255, 151, 29)
        //         滑块滑动停止后才触发ValueChanged事件
        //        slider.isContinuous = false
        
        slider.addTarget(self, action: #selector(PlayHeaderView.change(slider:)), for: .valueChanged)
        slider.addTarget(self, action: #selector(PlayHeaderView.sliderDragUp(sender:)), for: .touchUpInside)
        return slider
    }()
    
    private lazy var currentTime:UILabel = {
        let label = UILabel.init(frame: FRAME_CGFloat(0, 13, 75, 15))
        label.text = "00:00"
        label.font = UIFont.systemFont(ofSize: 15)
        label.textColor = DominantColor
        label.textAlignment = .center
        return label
    }()
    
    private lazy var totalTime:UILabel = {
        let label = UILabel.init(frame: FRAME_CGFloat(SCREEN_WIDTH - 75, 13, 75, 15))
        label.text = "00:00"
        label.font = UIFont.systemFont(ofSize: 15)
        label.textColor = DominantColor
        label.textAlignment = .center
        return label
    }()
    
    private lazy var playBtn:UIButton = {
        let button = UIButton(type: UIButton.ButtonType.custom)
        button.frame = FRAME_CGFloat(SCREEN_WIDTH / 2 - 15, SCREEN_SCALE_X(x: 188) + 44, 30, 30)
        button.setImage(UIImage(named: "icon_play"), for: .normal)
        button.addTarget(self, action: #selector(playBtn(button:)), for: .touchUpInside)
        return button
    }()
    
    private lazy var prevBtn:UIButton = {
        let button = UIButton(type: UIButton.ButtonType.custom)
        button.frame = FRAME_CGFloat(SCREEN_WIDTH / 2 - 80, SCREEN_SCALE_X(x: 188) + 44, 30, 30)
        button.setImage(UIImage(named: "icon_last"), for: .normal)
        button.tag = 21
        button.addTarget(self, action: #selector(nextBtn(button:)), for: .touchUpInside)
        return button
    }()
    
    private lazy var nextBtn:UIButton = {
        let button = UIButton(type: UIButton.ButtonType.custom)
        button.frame = FRAME_CGFloat(SCREEN_WIDTH / 2 + 50, SCREEN_SCALE_X(x: 188) + 44, 30, 30)
        button.setImage(UIImage(named: "icon_next"), for: .normal)
        button.tag = 22
        button.addTarget(self, action: #selector(nextBtn(button:)), for: .touchUpInside)
        return button
    }()
    
    private lazy var msgBtn:UIButton = {
        let button = UIButton(type: UIButton.ButtonType.custom)
        button.frame = FRAME_CGFloat(15, SCREEN_SCALE_X(x: 188) + 44, 30, 30)
        button.setImage(UIImage(named: "icon_liebiao"), for: .normal)
        button.addTarget(self, action: #selector(msgBtnAction), for: .touchUpInside)
        return button
    }()
    
    private lazy var timingBtn:UIButton = {
        let button = UIButton(type: UIButton.ButtonType.custom)
        button.frame = FRAME_CGFloat(SCREEN_WIDTH - 45, SCREEN_SCALE_X(x: 188) + 44, 30, 30)
        button.setImage(UIImage(named: "icon_block"), for: .normal)
        button.addTarget(self, action: #selector(timingBtnAction), for: .touchUpInside)
        return button
    }()
    
    private lazy var headImageView:UIImageView = {
        let imageView = UIImageView.init(frame: FRAME_CGFloat(33, SCREEN_SCALE_X(x: 188) + 94 + 10, 48, 48))
        return imageView
    }()
    
    private lazy var lineView:UIView = {
        let imageView = UIView.init(frame: FRAME_CGFloat(20, SCREEN_SCALE_X(x: 188) + 94, SCREEN_WIDTH - 40, 1))
        imageView.backgroundColor = RGB_Same(240, 1)
        return imageView
    }()
    
    private lazy var titleLabel:UILabel = {
        let label = UILabel.init(frame: FRAME_CGFloat(91, SCREEN_SCALE_X(x: 188) + 94 + 12.5, SCREEN_WIDTH - 91 - 45, 24))
        label.text = "--"
        label.font = Font_Medium(17)
        label.textColor = RGB_Same(53)
        label.textAlignment = .left
        return label
    }()
    
    private lazy var listenNumLabel:UILabel = {
        let label = UILabel.init(frame: FRAME_CGFloat(91, SCREEN_SCALE_X(x: 188) + 94 + 39.5, SCREEN_WIDTH - 91 - 45, 20))
        label.text = "--"
        label.font = Font_Regular(14)
        label.textColor = RGB_Same(53)
        label.textAlignment = .left
        return label
    }()
    
    lazy var collectBtn:UIButton = {
        let button = UIButton(type: UIButton.ButtonType.custom)
        button.frame = FRAME_CGFloat(SCREEN_WIDTH - 41, SCREEN_SCALE_X(x: 188) + 94 + 21, 22, 22)
        //        button.setImage(UIImage(named: "icon_star_off"), for: .normal)
        button.addTarget(self, action: #selector(collectionAction(button:)), for: .touchUpInside)
        return button
    }()
    
    var playTrackInfo:PlayDetailsModel?{
        didSet{
            guard let model = playTrackInfo else {return}
            self.imageView.sd_setImage(with: URL(string: StringIncludeChineseToString(model.detailImageUrl ?? "1")), completed: nil)
            self.headImageView.sd_setImage(with: URL(string: StringIncludeChineseToString(model.shareImageUrl ?? "1")), completed: nil)
            self.titleLabel.text = model.title ?? ""
            self.listenNumLabel.text = "\(model.listenNum)人收听"
            self.getCollectState()
            self.ifSame()
            self.ifSamePlay()
            //            if model.markStatus == 1 {
            //                self.collectBtn.setImage(IMAGE(name: "icon_star_off"), for: .normal)
            //                self.collectBtn.tag = 21
            //            } else {
            //                self.collectBtn.setImage(IMAGE(name: "icon_star_on"), for: .normal)
            //                self.collectBtn.tag = 22
            //            }
            
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.isUserInteractionEnabled = true
        setUpUI()
        
        
    }
    
    func setUpUI(){
        self.addSubview(self.imageView)
        self.addSubview(self.sliderBackView)
        self.sliderBackView.addSubview(self.slider)
        self.sliderBackView.addSubview(self.currentTime)
        self.sliderBackView.addSubview(self.totalTime)
        self.addSubview(self.playBtn)
        self.addSubview(self.prevBtn)
        self.addSubview(self.nextBtn)
        self.addSubview(self.msgBtn)
        self.addSubview(self.timingBtn)
        self.addSubview(self.lineView)
        self.addSubview(self.headImageView)
        self.addSubview(self.titleLabel)
        self.addSubview(self.listenNumLabel)
        self.addSubview(self.collectBtn)
        starTimer()
        
        
        
        
    }
    
    func getCollectState() {
        HomeRequestModel.getCollecState(parameters: ["userId":String.getUserId(), "programId":self.playTrackInfo?.id]) { (state) in
            if state {
                self.collectBtn.tag = 22
                self.collectBtn.setImage(IMAGE(name: "icon_star_on"), for: .normal)
            } else {
                self.collectBtn.tag = 21
                self.collectBtn.setImage(IMAGE(name: "icon_star_off"), for: .normal)
            }
        }
    }
    
    func getMMSSFromSS(duration:Int)->(String){
        var min = duration / 60
        let sec = duration % 60
        var hour : Int = 0
        if min >= 60 {
            hour = min / 60
            min = min % 60
            if hour > 0 {
                return String(format: "%02d:%02d:%02d", hour, min, sec)
            }
        }
        return String(format: "%02d:%02d", min, sec)
    }
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
    
    @objc func msgBtnAction() {
        delegate?.playHeaderViewAction()
    }
    
    @objc func timingBtnAction() {
        delegate?.timeBtnAction()
        
    }
    
    @objc func playBtn(button:UIButton){
        TTAudioPlayer.isIndextNum = TTAudioPlayer.indextNum
        if self.programId == TTAudioPlayer.programId {
            TTAudioPlayer.isSelected = !TTAudioPlayer.isSelected
            if TTAudioPlayer.isSelected {
                button.setImage(UIImage(named: "icon_delay"), for: .normal)
                if TTAudioPlayer.isFirstPlay {
                    TTAudioPlayer.uploadDate()
                    TTAudioPlayer.uploadProgress()
                    TTAudioPlayer.play()
                    starTimer()
                }else {
                    starTimer()
                    TTAudioPlayer.resume()
                }
            }else{
                button.setImage(UIImage(named: "icon_play"), for: .normal)
                removeTimer()
                TTAudioPlayer.pause()
            }
        } else {
            TTAudioPlayer.uploadDate()
            TTAudioPlayer.uploadProgress()
            TTAudioPlayer.firstPlay(proId: self.programId, musicModel: self.musicModel as! PlayListModel)
            TTAudioPlayer.isSelected = true
            if TTAudioPlayer.isSelected {
                button.setImage(UIImage(named: "icon_delay"), for: .normal)
                starTimer()
                if TTAudioPlayer.isFirstPlay {
                    
                    TTAudioPlayer.play()
                    if TTAudioPlayer.state().rawValue == 5 {
                        self.timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(setProgressTo), userInfo: nil, repeats: false)
                    }
                    //                    setProgressTo(progress: 60.0)
                    //                    starTimer()
                }else {
                    //                    starTimer()
                    TTAudioPlayer.resume()
                }
                
                
            }else{
                button.setImage(UIImage(named: "icon_play"), for: .normal)
                removeTimer()
                TTAudioPlayer.pause()
            }
        }
        
        
    }
    
    @objc func nextBtn(button:UIButton){
        delegate?.playNextBtnAction(tag: button.tag)
    }
    
    @objc func collectionAction(button:UIButton) {
        if button.tag == 21 {
            toCollect()
        } else if button.tag == 22 {
            noCollect()
        }
        
    }
    
    func ifSame() {
        if self.programId == TTAudioPlayer.programId {
            self.sliderBackView.isHidden = false
        } else {
            self.sliderBackView.isHidden = true
        }
    }
    
    func ifSamePlay() {
        if self.programId == TTAudioPlayer.programId {
            self.sliderBackView.isHidden = false
            if TTAudioPlayer.isSelected {
                playBtn.setImage(UIImage(named: "icon_delay"), for: .normal)
            } else {
                playBtn.setImage(UIImage(named: "icon_play"), for: .normal)
            }
            
        } else {
            self.sliderBackView.isHidden = true
            playBtn.setImage(UIImage(named: "icon_play"), for: .normal)
        }
    }
    
    func toCollect() {
        HomeRequestModel.increaseHistoryAndCollections(parameters: ["userId":String.getUserId(),"seasonId":TTAudioPlayer.sesionId,"status":2,"programId":TTAudioPlayer.programId,"h5Url":""]) { (success) in
            if success {
                self.collectBtn.tag = 22
                self.collectBtn.setImage(IMAGE(name: "icon_star_on"), for: .normal)
                TTAlertView.showMessage(message: "收藏成功")
            }
            
        }
    }
    func noCollect() {
        HomeRequestModel.delHistory(parameters: ["userId":String.getUserId(),"seasonId":TTAudioPlayer.sesionId,"status":2,"programId":TTAudioPlayer.programId,"h5Url":""]) { (success) in
            if success {
                self.collectBtn.tag = 21
                self.collectBtn.setImage(IMAGE(name: "icon_star_off"), for: .normal)
                TTAlertView.showMessage(message: "取消收藏")
            }
            
        }
    }
    
    func starTimer() {
        displayLink = CADisplayLink(target: self, selector: #selector(updateCurrentLabel))
        displayLink?.add(to: RunLoop.current, forMode: RunLoop.Mode.common)
    }
    
    func removeTimer() {
        displayLink?.invalidate()
        displayLink = nil
    }
}

extension NewPlayHeaderView {
    @objc func setUpTimesView() {
        let currentTime:Int = Int(TTAudioPlayer.audioPlayer.progress)
        self.currentTime.text = getMMSSFromSS(duration: currentTime)
        let progress = Float(TTAudioPlayer.audioPlayer.progress / TTAudioPlayer.audioPlayer.duration)
        slider.value = progress
        
    }
    @objc func updateCurrentLabel() {
        self.ifSame()
        let currentTime:Int = Int(TTAudioPlayer.audioPlayer.progress)
        self.currentTime.text = getMMSSFromSS(duration: currentTime)
        let progress = Float(TTAudioPlayer.audioPlayer.progress / TTAudioPlayer.audioPlayer.duration)
        slider.value = progress
        if TTAudioPlayer.audioPlayer.duration > 0.0 {
            if Int(TTAudioPlayer.audioPlayer.progress) == 1 {
                TTNotificationCenter.Post(Music_Play, obj: nil)
            }
            
            if Int(TTAudioPlayer.audioPlayer.progress) == Int(TTAudioPlayer.audioPlayer.duration) {
                TTNotificationCenter.Post(Music_Next, obj: nil)
                //                self.playBtn.setImage(UIImage(named: "icon_play"), for: .normal)
                //                playNextSong()
                //                delegate?.playNextBtnActghccsion(tag: 22)
            }
        }
        self.totalTime.text = self.getMMSSFromSS(duration: Int(TTAudioPlayer.audioPlayer.duration))
        
        
    }
    @objc func change(slider:UISlider) {
        print("slider.value = %d",slider.value)
        TTAudioPlayer.audioPlayer.seek(toTime: Double(slider.value * Float(TTAudioPlayer.audioPlayer.duration)))
        
    }
    
    @objc func setProgressTo() {
        TTAudioPlayer.audioPlayer.seek(toTime: TTAudioPlayer.progressDoub)
        self.timer?.invalidate()
        self.timer = nil
        
    }
    
    @objc func sliderDragUp(sender: UISlider) {
        print("value:(sender.value)")
        
    }
    
    func playNextSong() {
        TTAudioPlayer.playNextSong()
        TTNotificationCenter.Post(ReloadPlayVcData, obj: nil)
    }
}
